using System;
using Common.Unity.Extensions.PropertyMapper.Policies;
using Microsoft.Practices.ObjectBuilder2;
using Common.Unity.Extensions;

namespace Common.Unity.Extensions.PropertyMapper
{
	class PropertyMappingContextStrategy : BuilderStrategy
	{
		public override void PreBuildUp(IBuilderContext context)
		{
			object source = context.GetBuildSource();
			if ( source != null )
			{
				NamedTypeBuildKey? buildKey = ResolveKey( context );
				if ( buildKey != null )
				{
					PropertyMappingKey key = new PropertyMappingKey( source.GetType(), buildKey.Value );
					PropertyMappingContext mappingContext = new PropertyMappingContext( key, source, context.Existing );
					context.Policies.SetDefault<IPropertyMappingContextPolicy>( new PropertyMappingContextPolicy( mappingContext ) );
				}
			}
		}

		static NamedTypeBuildKey? ResolveKey( IBuilderContext context )
		{
			if ( context.BuildKey is NamedTypeBuildKey )
			{
				return (NamedTypeBuildKey)context.BuildKey;
			}
			Type type;
			if ( BuildKey.TryGetType( context.BuildKey, out type ) )
			{
				return new NamedTypeBuildKey( type );
			}
			return null;
		}

		public override void PostBuildUp(IBuilderContext context)
		{
			context.Policies.ClearDefault<IPropertyMappingContextPolicy>();
		}
	}
}